//
//  CLReadViewScrollController.m
//  CLBrowser
//
//  Created by 梁慧聪 on 2022/7/23.
//

#import "CLReadViewScrollController.h"
#import "CLReadController.h"
#import "CLReadViewStatusTopView.h"
#import "CLTableView.h"
#import "CLReadViewStatusBottomView.h"
#import "CLReadHomeViewCell.h"
#import "CLReadViewCell.h"
#import "CLReadTextFastParser.h"
@interface CLReadViewScrollController ()<UITableViewDelegate,UITableViewDataSource>
/// 当前主控制器
//@property (nonatomic, weak) CLReadController *vc;

/// 顶部状态栏
@property (nonatomic, strong) CLReadViewStatusTopView *topView;

/// 阅读视图
@property (nonatomic, strong) CLTableView *tableView;

/// 底部状态栏
@property (nonatomic, strong) CLReadViewStatusBottomView *bottomView;

/// 当前阅读章节ID列表(只会存放本次阅读的列表)
@property (nonatomic, strong) NSMutableArray <NSString*>*chapterIDs;

/// 当前正在加载的章节
@property (nonatomic, strong) NSMutableArray <NSString*>*loadChapterIDs;

/// 当前阅读的章节列表,通过已有的章节ID列表,来获取章节模型。
@property (nonatomic, strong) NSMutableDictionary <NSString *, CLReadChapterModel*>*chapterModels;

/// 记录滚动坐标
@property (nonatomic, assign) CGPoint scrollPoint;

/// 是否为向上滚动
@property (nonatomic, assign) BOOL isScrollUp;
@end

@implementation CLReadViewScrollController

- (void)viewDidLoad {
    [super viewDidLoad];
    _chapterIDs = [NSMutableArray array];
    _loadChapterIDs = [NSMutableArray array];
    // 阅读记录开始阅读
    [self.chapterIDs addObject:self.vc.readModel.recordModel.chapterModel.chapterid];
    
    // 刷新阅读进度
    [self reloadProgress];
    
    // 定位上次阅读位置
    [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.vc.readModel.recordModel.page inSection:0] atScrollPosition:(UITableViewScrollPositionTop) animated:NO];
}

- (void)addSubviews {
    [super addSubviews];
    
    // 阅读使用范围
    CGRect readRect = CL_READ_RECT();
    
    // 顶部状态栏
    CLReadViewStatusTopView *topView = [[CLReadViewStatusTopView alloc]init];
    self.topView = topView;
    topView.bookName.text = self.vc.readModel.title;
    topView.chapterName.text = self.vc.readModel.recordModel.chapterModel.name;
    [self.view addSubview:topView];
    topView.frame = CGRectMake(CGRectGetMinX(readRect), CGRectGetMinY(readRect), readRect.size.width, CL_READ_STATUS_TOP_VIEW_HEIGHT);
    
    // 阅读视图
    CLTableView *tableView = [[CLTableView alloc]init];
    self.tableView = tableView;
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.showsVerticalScrollIndicator = NO;
    tableView.showsHorizontalScrollIndicator = NO;
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:tableView];
    tableView.frame = CL_READ_VIEW_RECT();
    
    // 底部状态栏
    CLReadViewStatusBottomView *bottomView = [[CLReadViewStatusBottomView alloc]init];
    self.bottomView = bottomView;
    [self.view addSubview:bottomView];
    bottomView.frame = CGRectMake(CGRectGetMinX(readRect), CGRectGetMaxY(readRect) - CL_READ_STATUS_BOTTOM_VIEW_HEIGHT, readRect.size.width, CL_READ_STATUS_BOTTOM_VIEW_HEIGHT);
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.chapterIDs.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    NSString *chapterID = self.chapterIDs[section];
    
    // 获取章节内容模型
    CLReadChapterModel *chapterModel = [self getChapterModel:chapterID];
    
    // 有数据则返回页数
    if (chapterModel != nil) { return chapterModel.pageCount;}
    
    // 没有数据或者正在加载
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSString *chapterID = self.chapterIDs[indexPath.section];
    
    CLReadChapterModel *chapterModel = [self getChapterModel:chapterID];
    
    CLReadPageModel *pageModel = chapterModel.pageModels[indexPath.row];
    
    // 是否为书籍首页
    if (pageModel.isHomePage) {
        
        CLReadHomeViewCell *cell = [CLReadHomeViewCell cell:tableView];
        
        cell.homeView.readModel = self.vc.readModel;
        
        return cell;
        
    }else{
        
        CLReadViewCell *cell = [CLReadViewCell cell:tableView];
        
        cell.pageModel = pageModel;
        
        return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSString *chapterid = self.chapterIDs[indexPath.section];
    
    CLReadChapterModel *chapterModel = [self getChapterModel:chapterid];
    
    return chapterModel.pageModels[indexPath.row].cellHeight;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return CL_SPACE_MIN_HEIGHT;
}

- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section {
    
    NSString *chapterid = self.chapterIDs[section];
    
    CLReadChapterModel *chapterModel = [self getChapterModel:chapterid];
    
    // 预加载上一章
    [self preloadingPrevious:chapterModel];
    
    // 预加载下一章
    [self preloadingNext:chapterModel];
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.row != 0) { return; }
    
    NSString *chapterid = self.chapterIDs[indexPath.section];
    
    CLReadChapterModel *chapterModel = [self getChapterModel:chapterid];
    
    CLReadPageModel *pageModel = chapterModel.pageModels[indexPath.row];
    
    if (pageModel.isHomePage) {
        
        self.topView.hidden = YES;
        
        self.bottomView.hidden = YES;
    }
}

- (void)tableView:(UITableView *)tableView didEndDisplayingCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.row != 0) { return; }
    
    NSString *chapterid = self.chapterIDs[indexPath.section];
    
    CLReadChapterModel *chapterModel = [self getChapterModel:chapterid];
    
    CLReadPageModel *pageModel = chapterModel.pageModels[indexPath.row];
    
    if (pageModel.isHomePage) {
        
        self.topView.hidden = NO;
        
        self.bottomView.hidden = NO;
    }
}

// MARK: 监控滚动以及拖拽
// 开始拖拽
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    
    // 隐藏菜单
    [self.vc.readMenu showMenu:NO];
    
    // 重置属性
    self.isScrollUp = YES;
    self.scrollPoint = CGPointZero;
}
// 结束拖拽
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    // 更新阅读记录
    [self updateReadRecord:self.isScrollUp];
}
// 开始减速
- (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView {
    // 更新阅读记录
    [self updateReadRecord:self.isScrollUp];
}
// 结束减速
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    // 更新阅读记录
    [self updateReadRecord:self.isScrollUp];
}
// 正在滚动
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
    if (CGPointEqualToPoint(CGPointZero, self.scrollPoint)) { return; }
    
    CGPoint point = [[scrollView panGestureRecognizer] translationInView:scrollView];
    
    if (point.y < self.scrollPoint.y) { // 上滚
        
        self.isScrollUp = YES;
        
    }else if (point.y > self.scrollPoint.y) { // 下滚
        
        self.isScrollUp = NO;
        
    }else{ }
    
    // 记录坐标
    self.scrollPoint = point;
}

// MARK: 阅读记录以及进度
/// 更新阅读记录(滚动模式) isRollingUp:是否为往上滚动
- (void)updateReadRecord:(BOOL)isRollingUp {
    WEAK_SELF;
    NSArray *indexPaths = [self.tableView indexPathsForVisibleRows];
    
    // 异步更新(推荐使用异步)
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
        if (indexPaths != nil && !indexPaths.isEmpty) {
            NSIndexPath *indexPath = isRollingUp ? indexPaths.lastObject : indexPaths.firstObject;
            
            NSString *chapterid = weakSelf.chapterIDs[indexPath.section];
            
            CLReadChapterModel *chapterModel = [weakSelf getChapterModel:chapterid];
            
            [weakSelf.vc.readModel.recordModel modify:chapterModel page:indexPath.row];
            
            CL_READ_RECORD_CURRENT_CHAPTER_LOCATION = weakSelf.vc.readModel.recordModel.locationFirst;
            
            dispatch_main_safe_async(^{
                weakSelf.topView.chapterName.text = chapterModel.name;
                
                [weakSelf reloadProgress];
            });
        }
    });
}

- (void)reloadProgress {
    //DZM_READ_TOTAL_PROGRESS
    if ([CLReadConfigure sharedInstance].progressType == CLProgressTypeTotal) {// 总进度
        CGFloat progress = [self CL_READ_TOTAL_PROGRESS:self.vc.readModel recordModel:self.vc.readModel.recordModel];
        self.bottomView.progress.text = CL_READ_TOTAL_PROGRESS_STRING(progress);
    } else {// 分页进度
        self.bottomView.progress.text = [NSString stringWithFormat:@"%@/%@",@(self.vc.readModel.recordModel.page + 1),@(self.vc.readModel.recordModel.chapterModel.pageCount)];
    }
}

- (CLReadChapterModel *)getChapterModel:(NSString *)chapterid {
    
    CLReadChapterModel *chapterModel = nil;
    
    if ([self.chapterModels.allKeys containsObject:chapterid]) {// 内存中存在章节内容
        chapterModel = self.chapterModels[chapterid];
    } else {// 内存中不存在章节列表
        // 检查是否存在章节内容
        BOOL isExist = [CLReadChapterModel isExist:self.vc.readModel.bookid chapterid:chapterid];
        // 存在 || 不存在(但是为本地阅读)
        if (isExist || self.vc.readModel.bookSourceType == BookSourceTypeLocal) {
            // 获取章节数据
            if (!isExist) {
                chapterModel = [CLReadTextFastParser parser:self.vc.readModel chapterid:chapterid];
            } else {
                chapterModel = (CLReadChapterModel *)[CLReadChapterModel model:self.vc.readModel.bookid chapterid:chapterid isUpdateFont:YES];
            }
            self.chapterModels[chapterid] = chapterModel;
        }
    }
    return chapterModel;
}
/// 预加载上一个章节
- (void)preloadingPrevious:(CLReadChapterModel *)chapterModel {
    WEAK_SELF;
    // 章节ID
    NSString *chapterID = chapterModel.previousChapterID;
    
    // 是否有章节 || 是否为第一章 || 是否正在加载 || 是否已经存在阅读列表
    if (chapterModel == nil || chapterModel.isFirstChapter || [self.loadChapterIDs containsObject:chapterID] || [self.chapterIDs containsObject:chapterID]) { return; }
    
    // 加入加载列表
    [self.loadChapterIDs addObject:chapterID];
    
    // 书籍ID
    NSString *bookID = chapterModel.bookid;
    
    // 预加载下一章
    // DispatchQueue.global().async { [weak self] () in
    // 由于字典在异步下存在线程安全，这里换成同步，防止字典内对象中途释放或者野指针
    dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        // 检查是否存在章节内容
        BOOL isExist = [CLReadChapterModel isExist:bookID chapterid:chapterID];
        
        // 存在 || 不存在(但是为本地阅读)
        if (isExist || weakSelf.vc.readModel.bookSourceType == BookSourceTypeLocal) {
            
            // 章节内容
            CLReadChapterModel *tempChapterModel = nil;
            
            // 获取章节数据
            if (!isExist) {
            
                // 章节还没从全文里面解析出来，需要解析出来使用
                tempChapterModel = [CLReadTextFastParser parser:weakSelf.vc.readModel chapterid:chapterID];
                
            }else{

                // 本地存在章节，取出来使用
                tempChapterModel = [CLReadChapterModel model:bookID chapterid:chapterID];
            }
        
            // 加入阅读内容列表
            weakSelf.chapterModels[chapterID] = tempChapterModel;
            
            dispatch_main_safe_async(^{
                STRONG_SELF;
                
                // 当前章节索引
                NSInteger previousIndex = MAX(0, [strongSelf.chapterIDs indexOfObject:chapterModel.chapterid] - 1);
                
                // 加载列表索引
                NSInteger loadIndex = [strongSelf.loadChapterIDs indexOfObject:chapterID];
                
                // 阅读章节ID列表加入
                [strongSelf.chapterIDs insertObject:chapterID atIndex:previousIndex];
                
                // 移除加载列表
                [strongSelf.loadChapterIDs removeObjectAtIndex:loadIndex];
                
                // 刷新
                [strongSelf.tableView reloadData];
                
                // 定位
                strongSelf.tableView.contentOffset = CGPointMake(0, strongSelf.tableView.contentOffset.y + tempChapterModel.pageTotalHeight);
            });
            
            
        }else{ // 加载网络章节数据
            
            // ----- 搜索网络小说，多对照上面本地存在的步骤 -----
            
            // 加载章节数据
//                NJHTTPTool.request_novel_read(bookID, chapterID) { [weak self] (type, response, error) in
//
//                    if type == .success {
//
//                        // 获取章节数据
//                        let data = HTTP_RESPONSE_DATA_DICT(response)
//
//                        // 解析章节数据
//                        let tempChapterModel = DZMReadChapterModel(data)
//
//                        // 章节类容需要进行排版一篇
//                        tempChapterModel.content = DZMReadParser.contentTypesetting(content: chapterModel.content)
//
//                        // 保存
//                        tempChapterModel.save()
//
//                        // 加入阅读内容列表
//                        self?.chapterModels[chapterID!.stringValue] = tempChapterModel
//
//                        // 当前章节索引
//                        let previousIndex = max(0, (self!.chapterIDs.index(of: chapterModel.id)! - 1))
//
//                        // 加载列表索引
//                        let loadIndex = self!.loadChapterIDs.index(of: chapterID!)!
//
//                        // 阅读章节ID列表加入
//                        self?.chapterIDs.insert(chapterID!, at: previousIndex)
//
//                        // 移除加载列表
//                        self?.loadChapterIDs.remove(at: loadIndex)
//
//                        // 刷新
//                        self?.tableView.reloadData()
//
//                        // 定位
//                        self?.tableView.contentOffset = CGPoint(x: 0, y: self!.tableView.contentOffset.y + chapterModel.pageTotalHeight)
//                    }
//                }
        }
    });
}
/// 预加载下一个章节
- (void)preloadingNext:(CLReadChapterModel *)chapterModel {
    WEAK_SELF;
    // 章节ID
    NSString *chapterID = chapterModel.nextChapterID;
    
    // 是否有章节 || 是否为最后一章 || 是否正在加载 || 是否已经存在阅读列表
    if (chapterModel == nil || chapterModel.isFirstChapter || [self.loadChapterIDs containsObject:chapterID] || [self.chapterIDs containsObject:chapterID]) { return; }
    
    // 加入加载列表
    [self.loadChapterIDs addObject:chapterID];
    
    // 书籍ID
    NSString *bookID = chapterModel.bookid;
    
    // 预加载下一章
    // DispatchQueue.global().async { [weak self] () in
    // 由于字典在异步下存在线程安全，这里换成同步，防止字典内对象中途释放或者野指针
    dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        // 检查是否存在章节内容
        BOOL isExist = [CLReadChapterModel isExist:bookID chapterid:chapterID];
        
        // 存在 || 不存在(但是为本地阅读)
        if (isExist || weakSelf.vc.readModel.bookSourceType == BookSourceTypeLocal) {
            
            // 章节内容
            CLReadChapterModel *tempChapterModel = nil;
            
            // 获取章节数据
            if (!isExist) {
                
                // 章节还没从全文里面解析出来，需要解析出来使用
                tempChapterModel = [CLReadTextFastParser parser:weakSelf.vc.readModel chapterid:chapterID];
            
            }else{
                
                // 本地存在章节，取出来使用
                tempChapterModel = [CLReadChapterModel model:bookID chapterid:chapterID];
            }
            
            // 加入阅读内容列表
            weakSelf.chapterModels[chapterID] = tempChapterModel;
            
            dispatch_main_safe_async(^{
                STRONG_SELF;
                // 当前章节索引
                NSInteger nextIndex = [strongSelf.chapterIDs indexOfObject:chapterModel.chapterid] + 1;
                
                // 加载列表索引
                NSInteger loadIndex = [strongSelf.loadChapterIDs indexOfObject:chapterID];
                
                // 阅读章节ID列表加入
                [strongSelf.chapterIDs insertObject:chapterID atIndex:nextIndex];
                
                // 移除加载列表
                [strongSelf.loadChapterIDs removeObjectAtIndex:loadIndex];
                
                // 刷新
                [strongSelf.tableView insertSections:[NSIndexSet indexSetWithIndex:nextIndex] withRowAnimation:UITableViewRowAnimationNone];
            });
        }else{ // 加载网络章节数据
            
            // ----- 搜索网络小说，多对照上面本地存在的步骤 -----
            
//                // 加载章节数据
//                NJHTTPTool.request_novel_read(bookID, chapterID) { [weak self] (type, response, error) in
//
//                    if type == .success {
//
//                        // 获取章节数据
//                        let data = HTTP_RESPONSE_DATA_DICT(response)
//
//                        // 解析章节数据
//                        let tempChapterModel = DZMReadChapterModel(data)
//
//                        // 章节类容需要进行排版一篇
//                        tempChapterModel.content = DZMReadParser.contentTypesetting(content: chapterModel.content)
//
//                        // 保存
//                        tempChapterModel.save()
//
//                        // 加入阅读内容列表
//                        self?.chapterModels[chapterID!.stringValue] = tempChapterModel
//
//                        // 当前章节索引
//                        let nextIndex = self!.chapterIDs.index(of: chapterModel.id)! + 1
//
//                        // 加载列表索引
//                        let loadIndex = self!.loadChapterIDs.index(of: chapterID!)!
//
//                        // 阅读章节ID列表加入
//                        self?.chapterIDs.insert(chapterID!, at: nextIndex)
//
//                        // 移除加载列表
//                        self?.loadChapterIDs.remove(at: loadIndex)
//
//                        // 刷新
//                        self?.tableView.insertSections(IndexSet(integer: nextIndex), with: .none)
//                    }
//                }
        }
    });
}


@end
